package com.bum.guru.baucua.bo;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.math.RandomUtils;

import com.asao.baseware.core.util.MD5;
import com.bum.api.core.exp.om.Metas;
import com.bum.api.core.exp.om.Params;
import com.bum.api.core.exp.util.ChainMap;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class BauCuaJsonBO {
	Gson			gson;
	private double	rate	= 0.9f;

	public String getToken() {
		return MD5.instance.md5(System.currentTimeMillis() + "#(*$^&" + RandomUtils.nextDouble());
	}

	public String request(String path, Params params, Metas metas) {
		return gson.toJson(ChainMap.map()
				.put("balance", 1000000L)
				.put("token", getToken())
				.put("timeBet", 15)
				.put("timeRoll", 5)
				.put("watchCountLimit", 10)
				.get());
	}

	Type	listLongs	= new TypeToken<ArrayList<Long>>()
						{
						}.getType();

	public String commit(String path, Params params, Metas metas) {
		String doorsText = params.getValue("doors");

		List<Long> doors = gson.fromJson("[" + doorsText + "]", listLongs);

		long total = 0L;
		for (Long door : doors) {
			total -= door;
		}

		long[] doorResults = new long[] {
				0, 0, 0, 0, 0, 0
		};

		int[] dices = Dice.roll();
		
		if (total < 0) {
			for (int dice : dices) {
				if (doors.get(dice) > 0) {
					double gain = Math.ceil(doors.get(dice) * rate);

					doorResults[dice] += gain;
					total += gain;
				}
			}

			for (int i = 0; i < doorResults.length; i++) {
				if (doorResults[i] > 0) {
					total += doors.get(i);
				}
			}
			
			
		}

		return gson.toJson(ChainMap.map()
				.put("dices", dices)
				.put("doors", doorResults)
				.put("balance", 1000000L)
				.get());
	}

	public void setGson(Gson gson) {
		this.gson = gson;
	}
}
